import os
from datetime import datetime

def rename_files_with_date(directory):
    try:
        # 获取当前日期字符串
        date_str = datetime.now().strftime('%Y%m%d')
        
        # 遍历目录下的所有文件
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            
            # 跳过目录，只处理文件
            if os.path.isfile(file_path):
                # 分离文件名和扩展名
                name, ext = os.path.splitext(filename)
                
                # 构造新文件名
                new_name = f"{date_str}_file_{name}{ext}"
                new_path = os.path.join(directory, new_name)
                
                # 避免覆盖已存在的文件
                if not os.path.exists(new_path):
                    os.rename(file_path, new_path)
                    print(f'Renamed: {filename} -> {new_name}')
                else:
                    print(f'Skipped: {new_name} already exists')
        
        print('批量重命名完成！')
    except Exception as e:
        print(f'发生错误: {str(e)}')

if __name__ == '__main__':
    target_dir = 'd:/images'
    
    if os.path.exists(target_dir):
        rename_files_with_date(target_dir)
    else:
        print(f'错误：目录 {target_dir} 不存在')
    
    input('按回车键退出...')